package com.lyw.forum.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.lyw.forum.common.enums.ResultCode;
import com.lyw.forum.common.exception.ApplicationException;
import com.lyw.forum.common.utils.BeanTransUtils;
import com.lyw.forum.common.utils.SetDefaultUtils;
import com.lyw.forum.mapper.MessageMapper;
import com.lyw.forum.pojo.dataobject.Message;
import com.lyw.forum.pojo.request.MessageCreateRequest;
import com.lyw.forum.pojo.response.AppResult;
import com.lyw.forum.pojo.response.MessageSelectResponse;
import com.lyw.forum.pojo.response.UserSelectResponse;
import com.lyw.forum.service.IMessageService;
import com.lyw.forum.service.IUserService;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Slf4j
@Service
public class MessageServiceImpl implements IMessageService {

    @Resource
    private MessageMapper messageMapper;

    @Resource
    private IUserService userService;

    @Override
    public void create(MessageCreateRequest messageCreateRequest) {
        //转换
        Message message = BeanTransUtils.transMessageCreateRequest(messageCreateRequest);

        //校验接收者是否存在
        UserSelectResponse userSelectResponse = userService.selectById(message.getReceiveUserId());

        if (userSelectResponse == null) {
            //打印日志
            log.error(ResultCode.FAILED_USER_NOT_EXISTS + ", id: " + message.getReceiveUserId());
            //抛出异常
            throw new ApplicationException(AppResult.fail(ResultCode.FAILED_USER_NOT_EXISTS));
        }

        //设置默认值
        message = SetDefaultUtils.setMessageRequestDefault(message);

        //调用mapper
        int insert = messageMapper.insert(message);

        if (insert <= 0) {
            //打印日志
            log.error(ResultCode.FAILED_CREATE.toString());
            //返回响应
            throw new RuntimeException(ResultCode.FAILED_CREATE.getMessage());
        }

    }

    @Override
    public MessageSelectResponse selectById(Integer id) {
        //非空校验
        if (id == null || id < 1) {
            //打印日志
            log.error(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            //抛出异常
            throw new ApplicationException(AppResult.fail(ResultCode.FAILED_PARAMS_VALIDATE));
        }

        //调用mapper
        Message message = messageMapper.selectById(id);

        //转换结果
        MessageSelectResponse messageSelectResponse = BeanTransUtils.transMessage(message);

        //返回结果
        return messageSelectResponse;
    }

    @Override
    public Integer selectUnreadCount(Integer id) {
        //调用mapper
        LambdaQueryWrapper<Message> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Message::getState, (byte) 0)
                .eq(Message::getDeleteState, (byte) 0)
                .eq(Message::getReceiveUserId, id);

        Long result = messageMapper.selectCount(wrapper);

        if (result == null) {
            log.error(ResultCode.ERROR_SERVICES.toString());
            throw new ApplicationException(AppResult.fail(ResultCode.ERROR_SERVICES));
        }

        return result.intValue();
    }

    @Override
    public List<MessageSelectResponse> selectByReceiveUserId(Integer receiveUserId) {
        //调用mapper
        List<Message> messages = messageMapper.selectByReceiveUserId(receiveUserId);

        //转换结果
        List<MessageSelectResponse> messageSelectResponses = BeanTransUtils.transMessage(messages);

        //返回结果
        return messageSelectResponses;
    }

    @Override
    public void updateStateById(Integer id, Byte state) {
        //非空校验
        if (id == null || id < 1 || state == null || state < 0 || state > 2) {
            //打印日志
            log.error(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            //抛出异常
            throw new ApplicationException(AppResult.fail(ResultCode.FAILED_PARAMS_VALIDATE));
        }

        //创建一个更新的用户对象
        Message message = new Message();
        message.setId(id);
        message.setState(state);
        message.setUpdateTime(new Date());

        //调用mapper
        int update = messageMapper.updateById(message);
        if (update != 1) {
            //打印日志
            log.error(ResultCode.FAILED_UPDATE.toString());
            //抛出异常
            throw new ApplicationException(AppResult.fail(ResultCode.FAILED_UPDATE));
        }
    }

    @Override
    public void reply(Integer repliedId, MessageCreateRequest messageCreateRequest) {
        //校验被回复者的栈内信是否存在
        MessageSelectResponse messageSelectResponse = selectById(repliedId);

        if (messageSelectResponse == null || messageSelectResponse.getDeleteState() == 1) {
            //打印日志
            log.error(ResultCode.FAILED_NOT_EXISTS.toString());
            //抛出异常
            throw new ApplicationException(AppResult.fail(ResultCode.FAILED_NOT_EXISTS));
        }

        //更新状态位已回复
        updateStateById(repliedId, (byte) 2);

        //把回复的内容写入数据库
        create(messageCreateRequest);
    }
}
